var url = null;
var refreshInterval = null;
var callback = null;
var version = 1;
var isVisualizationLoaded = false;
var query = null;
var heartbeatTimerId = 0;
                
function getData(url, refreshInterval, callback, version) {
    this.url = url;
    this.refreshInterval = refreshInterval;
    this.callback = callback;

    if (version)
	this.version = version;
    
    //For some reason, trying to load the Visualization API more than once does not execute the callback function.
    if (!isVisualizationLoaded) {
	loadVisualizationAPI();
    }
    else {
	sendQuery();
    }
}

/**
* Load the APIs and run sendQuery when the load is complete
*/
function loadVisualizationAPI() {
    isVisualizationLoaded = true;
    google.load("visualization", "1", {"callback" : sendQuery});
}

/**
* Create a query , then send it to the spreadsheet data source.
*  Also give the name of a function ("handleQueryResponse") to
*  run once the spreadsheet data is retrieved.
*/
function sendQuery() {
    if (query !== null) {
        query.abort(); //Stop the automated query sending set by Refresh Interval.
    }
    
    query = new google.visualization.Query(url);
    query.setRefreshInterval(refreshInterval);

    if (version == 1)
	query.send(processResponseAsCustomJSON);
    else if (version == 2)
	query.send(processResponse);
}

/**
* The core logic. Process the spreadsheet data however you want. 
* In this case, we create HTML to be presented back to the user. 
* We'll use inline comments to provide a step-by-step description 
* of what we're doing:
*/
function processResponseAsCustomJSON(response) {
    var data, propertyName, label, item;
    var cols = new Array();
    var rows = new Array();
    var json = {
	"cols": [],
        "rows": []
    };
    
    restartHeartbeatTimer();

    //Get spreadsheet data.
    data = response.getDataTable();
    
    //Get the column headings.
    for (var col = 0; col < data.getNumberOfColumns(); col++) {
	label = new Object();
	//id property removes any whitespace from the column label.
	//label property is the unaltered column label.
	label["id"] = data.getColumnLabel(col).split(' ').join('');
	label["label"] = data.getColumnLabel(col);
        cols[col] = label;
    }
    
    //Get the row values.
    for (var row = 0; row < data.getNumberOfRows(); row++) {
        item = new Object();
        
        for (var col = 0; col < data.getNumberOfColumns(); col++) {
            propertyName = cols[col].id;
            item[propertyName] = data.getFormattedValue(row, col);
        }
        
        rows[row] = item;
    }

    json.cols = cols;
    json.rows = rows;
    
    //Call the callback function.
    callback(json);
}

function processResponse(response) {
    var data, text, json;
    
    restartHeartbeatTimer();

    //Get spreadsheet data.
    data = response.getDataTable();
    text = data.toJSON();
    json = JSON.parse(text);
    
    //Call the callback function.
    callback(json);
}
            
/**
* Monitor Visualization API refresh updates with Heartbeat Timer.
* This is a work around for Visualization API bug when it stops 
* refreshing data if data hadn't change for 2 consequent data requests.
*/
function restartHeartbeatTimer() {
    clearTimeout(heartbeatTimerId);
    var interval = 0;
    
    try
    {
        //Set Heartbeat Timer to 3x times longer then refresh interval.
	var interval = 3 * 1000 * refreshInterval;
    }
    catch(err)
    {}
    if (interval > 0) {
        heartbeatTimerId = setTimeout('sendQuery()', interval);
    }
}
                